class Stock < ActiveRecord::Base
  attr_accessible :commission_percentage, :company, :free_quantity, :name, :person_id, :purchase_quantity, :sale_cost, :tax_percentage, :total_purchase_cost, :purchase_date, :available_quantity

  belongs_to :person

  has_one :transaction, :as => :reference, :autosave => true
  accepts_nested_attributes_for :transaction, :allow_destroy => true,:reject_if => lambda { |a| a.valid? }

  validates :purchase_quantity,:available_quantity,:free_quantity, :numericality => { :only_integer => true, :greater_than => -1 }
  validates :total_purchase_cost,:sale_cost, :numericality => { :greater_than => 0 }
  validates :tax_percentage,:commission_percentage, :numericality => { :greater_than => 0, :less_than => 100.01 }

  before_validation :update_quantity,:on => :create

  def update_quantity
    self.available_quantity = self.purchase_quantity + self.free_quantity
  end

  def self.available_stocks
    find(:all, :conditions => ['available_quantity>0']) 
  end
end
